package com.haoniu.common.utils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

/**
 * 调用shell
 */
public class RunShellUtil {
    /**
     * 执行shell命令 String[] cmd = { "sh", "-c", "lsmod |grep linuxVmux" }或者
     * String[] cmd = { "sh", "-c", "./load_driver.sh" }
     */
    public static String runScript(String[] cmd) {
        StringBuffer buf = new StringBuffer();
        String rt = "-1";
        try {
            Process pos = Runtime.getRuntime().exec(cmd);
            pos.waitFor();
            InputStreamReader ir = new InputStreamReader(pos.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String ln = "";
            while ((ln = input.readLine()) != null) {
                buf.append(ln + "\n");
            }
            rt = buf.toString();
            input.close();
            ir.close();
        } catch (java.io.IOException e) {
            rt = e.toString();
        } catch (Exception e) {
            rt = e.toString();
        }
        return rt;
    }

    /**
     * 执行简单命令 String cmd="ls"
     */
    public static String runScript(String cmd) {
        StringBuffer buf = new StringBuffer();
        String rt = "-1";
        try {
            Process pos = Runtime.getRuntime().exec(cmd);
            pos.waitFor();
            InputStreamReader ir = new InputStreamReader(pos.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String ln = "";
            while ((ln = input.readLine()) != null) {
                buf.append(ln + "\n");
            }
            rt = buf.toString();
            input.close();
            ir.close();
        } catch (java.io.IOException e) {
            rt = e.toString();
        } catch (Exception e) {
            rt = e.toString();
        }
        return rt;
    }

    public void runC(){
        try {
            //程序路径
            String shpath="/usr/local/tomcat/manage/bin";
            Process process =null;
            String command1 = "cd " + shpath;
            process = Runtime.getRuntime().exec(command1);
            process.waitFor();
            //参数
//            String shpath2="/usr/local/tomcat/manage/bin/shutdown.sh";
//            String command2 = "/bin/sh " + shpath2;
            String command2 = "./shutdown.sh";
            Runtime.getRuntime().exec(command2).waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
       /* String[] cmd = { "sh", "/usr/local/tomcat/manage/bin/shutdown.sh" };
        System.out.println(runScript(cmd));*/
    }
}